// pages/todos/todos.js
Page({
  data: {
    input:"",
    todos:[
      {name:"Learning HTML",completed:true},
      {name:"Learning CSS",completed:false},
      {name:"Learning JavaScript",completed:false}
    ],
    leftcount:2,
    allcompleted:false
  },
  inputchangehadle:function(e){
    this.setData({
      input:e.detail.value
    })
  },

  addtodoshadle:function(){
    if(!this.data.input) return

    var todos=this.data.todos
    todos.push({
      name:this.data.input,
      completed:false
    })

    this.setData({
      todos:todos,
      input:'',
      leftcount:this.data.leftcount+1
    })
  },

  togglehadle:function(e){
    var item=this.data.todos[e.currentTarget.dataset.index]
    item.completed=!item.completed
    var leftcount = this.data.leftcount+ (item.completed ?-1:1)
    this.setData({
     todos:this.data.todos,
     leftcount:leftcount
    })
  },

  removehadle:function(e){
    var todos=this.data.todos
    var item=todos.splice(e.currentTarget.dataset.index,1)[0]
    var leftcount = this.data.leftcount+ (item.completed? 0:-1)
    this.setData({
     todos:todos,
     leftcount:leftcount
    })
  },

  toggleAllHadle:function(){
    this.data.allcompleted=!this.data.allcompleted
    var todos=this.data.todos
    var that=this
    
    todos.forEach(function(item){
      item.completed=that.data.allcompleted
    })
    var leftcount = this.data.allcompleted?0:this.data.todos.length
    this.setData({
      todos:todos,
      leftcount:leftcount
    })
  },
  clearHadle:function(){
    var todos=this.data.todos.filter(function(item){
      return !item.completed
    })

    this.setData({
      todos:todos
    })
  }
})

